
import React, { useEffect, useState } from 'react';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import { useDeviceData } from '../hooks/useDeviceData';
import { StandardBleConnector } from '../StandardBleDemo/components/leBleConnector';
import { RawBtn } from '../components/Btn';
import { ActionSheet } from '../components/ActionSheet';
import { NumberPanelControl, EnumPanelControl } from '../components/DeviceDataModal';
import './DeviceDetailBtn.less';

export function DeviceDetailBtn() {
  const [sdkReady, setSdkReady] = useState(false);
  const [state, {
    onDeviceDataChange,
    onDeviceStatusChange
  }] = useDeviceData(sdk);
  const weight_unit = state.templateMap.weight_unit.define.mapping
  const tempbattery_status = state.deviceData.battery_status == undefined ? "--" : state.deviceData.battery_status+'%'
  const unitindex = state.deviceData.weight_unit
  const [unit,setunit] = useState(weight_unit[unitindex])
  const [battery_status,setbattery_status] = useState(tempbattery_status)
  // 显示单位弹框
  const [isunit,setisunit] = useState(false)
  const [isconected,setisconected] = useState(false)
  
  // WebSocket 监听
  useEffect(() => {
    // 监听设备控制推送
    const handleWsControl = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('DeviceDetailBtn wsControl', deviceData);
    };
    // 监听设备上报数据推送
    const handleWsReport = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('DeviceDetailBtn wsReport', deviceId, deviceData);
    };
    // 监听设备在线状态变更推送
    const handleWsStatusChange = ({ deviceId, deviceStatus}) => {
      if (deviceId === sdk.deviceId) {
        onDeviceStatusChange(deviceStatus);
      }
      console.error('DeviceDetailBtn wsStatusChange', deviceId, deviceStatus );
    };

    sdk
      .on('wsControl', handleWsControl)
      .on('wsReport', handleWsReport)
      .on('wsStatusChange', handleWsStatusChange);

    return () => {
      sdk
        .off('wsControl', handleWsControl)
        .off('wsReport', handleWsReport)
        .off('wsStatusChange', handleWsStatusChange);
    };
  }, []);
  useEffect(() =>  {
		h5PanelSdk.sdkReady().then(() =>  setSdkReady(true));
	}, []);
  useEffect(() => {
    setunit(weight_unit[state.deviceData.weight_unit])
    setbattery_status(
      state.deviceData.battery_status+'%'
    )
    console.error(state.deviceData.battery_status)
    console.error(state.deviceData.weight_unit)
  }, [state]);
  function showunit(){
    console.log(isunit)
    setisunit(true)
  }
  
  function YactionSheet(props){
    // 单位页面
    function WeuList() {
      return (
        <div>
          {
            Object.keys(weight_unit).map((obj, idx) => (
              <div className="fl-lr pdtb bd1 mgb" key={idx} onClick={() =>changeUnit(idx)} >
                <div>{weight_unit[obj]}</div>
                <div><input type="radio" name="weight_unit" defaultChecked={unitindex === idx} value={weight_unit[obj]}/></div>
              </div>
            ))
          }
        </div>
      )
    }
    const onControlDeviceData = (id, value) => sdk.controlDeviceData({ [id]: value });
    const changeUnit = async (value) => {
      console.log(`selected ${value}`);
      await onControlDeviceData("weight_unit",value)
      setisunit(false)
      setunit(weight_unit[value])
      hidedevt()
    }
    console.log(props)
    const title =props.title
    const isshow = props.show
    // const [isunit,setisunit] = useState()
    function close(){
      setisunit(false)
    }
    function cofirm(){
      onControlDeviceData("weight_unit",value)
    }
    function cancle(){
      setisunit(false)
    }
    return (
      <>
      {isunit &&
      <div className="acsheel-con">
        <div className="acsheel">
          <div className="acsheel-head">
            <div className="actitle">{title}</div>
            <div className="acclose" onClick={close}>X</div>
          </div>
          <div className="acsheeltem">
            <div className="acitem">
              <WeuList />
            </div>
            {/* <div className="acsheel-foot">
              <div className="lfbtn-gr mgr" onClick={cancle}>取消</div>
              <div className="lfbtn mgl" onClick={cofirm}>确定</div>
            </div> */}
          </div>
        </div>
      </div>}
      </>
    )
  }
  const showDeviceDetail = () => {
  // const showDeviceDetail = () => {
    // const isConfirm = await sdk.tips.confirm('是否展示H5设备详情？');
    // const isConfirm = true
    // sdk.goDeviceDetailPage();
    // if (isConfirm) {
      // await sdk.tips.alert('当前选择H5设备详情');
      setisconected(true)
      sdk.showDeviceDetail({
        // deviceInfo: {

        // },
        labelWidth: 120,
        marginTop: 75,
        shareParams: {
          a: 'a',
          b: 'b',
        },
        extendItems: [
          {
            //   labelIcon: '',unit weight_unit[unitindex]
            label: '重量单位',
            content: unit,
            onClick: () => showunit(),
          },
          {
            label: '电量状态',
            content: battery_status,
            onClick: () => sdk.goDeviceInfoPage()
          },
        ],
        extendButtons: [
          {
            text: '关闭设备详情',
            type: '',
            onClick: () => hidedevt(),
          },
          {
            text: '删除设备',
            type: '',
            onClick: () => deldevt(),
          },
        ],
        // containerClassName: ""
      });
    // } else {
    //   // await sdk.tips.alert('当前选择原生设备详情');
    //   sdk.goDeviceDetailPage();
    // }
  };
  const hidedevt = async () => {
    await sdk.hideDeviceDetail()
    setisconected(false)
  }
  const deldevt = async () => {
    await sdk.tips.alert('请先连接蓝牙设备！');
    // await sdk.deleteDevice()
  }
  const isStandardBleDevice = sdk.isStandardBleDevice; 
  return  !sdkReady ? <div > loading...</div >  : (
    <>
    {isconected && (
      <div className="bleconecter">
        {isStandardBleDevice &&
          (<StandardBleConnector familyId={sdk.familyId} deviceId={sdk.deviceId} />)
        }
      </div>
    )}
    <RawBtn
      className="panel-more-btn"
      onClick={showDeviceDetail}
    >
      <div className="more-btn-icon" />
    </RawBtn>
    {isunit && (
      <YactionSheet title={"修改单位"} show={true}/>
    )}
    </>
  );
}
